<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/
namespace app\admin\controller\match;

use app\admin\model\merchant\Store;
use app\common\constant\Constant;
use app\common\controller\BackendApi;
use app\common\library\Map\Map;
use app\common\manager\LogManager;
use app\common\manager\MatchManager;
use app\common\model\Region;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 赛事管理
 *
 * @icon fa fa-circle-o
 */
class Match extends BackendApi
{

    /**
     * Match模型对象
     * @var \app\admin\model\Match
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Match;
        $this->view->assign("reviewStatusList", $this->model->getReviewStatusList());
        $this->view->assign("typeList", $this->model->getTypeList());
        $purview = $this->model::PURVIEW;
        $this->assignconfig('purview', $purview);
        $this->view->assign('purview', $purview);

    }


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['merchant','store'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    public function add()
    {
        $startTime = microtime(true);
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            if ($params['sign_start_date']){
                $params['sign_start_date'] = strtotime($params['sign_start_date']);
            }

            if ($params['sign_end_date']){
                $params['sign_end_date'] = strtotime($params['sign_end_date']);
            }

            if ($params['match_date']){
                $params['match_date'] = strtotime($params['match_date']);
            }

            if (bcmod($params['people_count'],$params['group_people_number']) != 0){
                throw new Exception('赛事人数与小组人数不对等');
            }

            if (bcmod($params['group_people_number'],$params['group_inner_numbers']) != 0){
                throw new Exception('赛事组人数与小组人数不对等');
            }

            if ($params['group_people_number']==$params['group_inner_numbers']){
                throw new Exception('赛事组人数与小组人数不可相等');
            }

            if (!empty($params['release_time'])){
                $params['release_time'] = strtotime($params['release_time']);
                if($params['release_time'] >= $params['match_date']){
                    throw new Exception('发布时间不能大于赛事开始时间');
                }
            }

            if ($params['s_id'] && $storeInfo = Store::where('id',$params['s_id'])->find()){
                $params['organizer'] = $storeInfo['store_name'];
            }

            if ($params['sign_start_date'] >= $params['sign_end_date']){
                throw new Exception('报名开始时间不能大于结束时间');
            }

            if ($params['sign_end_date'] >= $params['match_date']){
                throw new Exception('赛事开始时间不能小于报名结束时间');
            }


            $addressConfig = get_addon_config('address');
            $map = new Map($addressConfig);
            $location = $params['lat'].','.$params['lng'];
            $map->getInfoByLocation($location);
            $response = $map->getResponse();
            $response = json_decode($response, true);
            if (!empty($response) && isset($response['status']) && $response['status'] == 0 && !empty($response['result']) && !empty($response['result']['address_component'])) {
                $province = $response['result']['address_component']['province'] ?: '';
                $city = $response['result']['address_component']['city'] ?: '';
                $district = $response['result']['address_component']['district'] ?: '';
                $params['province'] = Region::where('name',$province)->value('city_code');
                $params['city'] = Region::where('name',$city)->value('city_code');
                $params['district'] = Region::where('name',$district)->value('city_code');
            }
            $params['ct_date'] = time();
            $params['up_date'] = time();
            $referee = $params['referee'];
            unset($params['referee']);
            $result = $this->model->allowField(true)->save($params);
            $insertId = $this->model->getLastInsID();
            $purviewInsert = [];
            if ($referee){
                $referee = explode(',',$referee);
                if (is_array($referee) && $referee){
                    foreach ($referee as $k=>$v){
                        $purviewInsert[] = [
                            'match_id'=>$insertId,
                            'user_id'=>$v,
                            'purview'=>!empty($params['purview'][$v]) ? implode(',',$params['purview'][$v]) : '',
                            'create_time'=>time(),
                            'update_time'=>time(),
                        ];
                    }
                }

                if ($purviewInsert){
                    $RefereeModel = new \app\admin\model\match\Referee();
                    $RefereeModel->saveAll($purviewInsert);
                }
            }


            if(!empty($params['banner_image'])){
                $insertImage = [];
                $banner_image = explode(',',$params['banner_image']);
                if ($banner_image && is_array($banner_image)){
                    foreach ($banner_image as $k=>$v){
                        $insertImage[] = [
                            'type'=>\app\common\model\RelationImage::TYPE_MATCH,
                            'relation_id'=>$insertId,
                            'url'=>$v,
                            'create_time'=>time(),
                        ];
                    }
                }

                if ($insertImage){
                    $RelationImageModel = new \app\common\model\RelationImage();
                    $RelationImageModel->saveAll($insertImage);
                }
            }

            $round = intval($params['rounds']);
            if ($round > 0){
                for ($i = 1; $i <= $round; $i++){
                    $insert[$i] = [
                        'match_id'=>$insertId,
                        'title'=>'第'.$i.'轮',
                        'create_time'=>time(),
                        'update_time'=>time(),
                    ];
                }

                $roundModel = new \app\admin\model\match\Round();
                $roundModel->saveAll($insert);
            }
            /*$redis = new \Redis();
            $config = config('redis');
            $redis->pconnect($config['host'],$config['port']);
            if ($config['password']){
                $redis->auth($config['password']);
            }
            $redis->hSet(Constant::getHashAllTeamKey($config['prefix']),$insertId,json_encode($this->model->getData()));*/

            $adminInfo = $this->auth->getUserInfo();
            //print_r($adminInfo);
            $endTime = microtime(true);
            hook('Log',[
                'username'=>$adminInfo['username'],
                'user_id'=>$adminInfo['id'],
                'tips'=>'创建赛事',
                'data'=>$params,
                'match_id'=>$insertId,
                'start_time'=>$startTime,
                'end_time'=>$endTime,
                'type'=>LogManager::TYPE_SERVER,
                'redirect'=>LogManager::MATCH_REDIRECT_PATH.date('Y').'/'.date('m').'/'.date('d'),
            ]);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function edit($ids=null)
    {
        $startTime = microtime(true);
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($row->sign_start_date){
            $row->sign_start_date = date('Y-m-d H:i:s',$row->sign_start_date);
        }

        if ($row->sign_end_date){
            $row->sign_end_date = date('Y-m-d H:i:s',$row->sign_end_date);
        }

        if ($row->match_date){
            $row->match_date = date('Y-m-d H:i:s',$row->match_date);
        }

        if ($row->release_time){
            $row->release_time = date('Y-m-d H:i:s',$row->release_time);
        }

        $image = \app\common\model\RelationImage::where('relation_id',$row->m_id)->where('type',\app\common\model\RelationImage::TYPE_MATCH)->select();

        $arr = [];
        if($image){
            foreach ($image as $k=>$v){
                $arr[] = $v->url;
            }
        }

        if ($arr){
            $row->banner_image = implode(',',$arr);
        }else{
            $row->banner_image = '';
        }

        $refereeModel = new \app\admin\model\match\Referee();
        $refereeInfo = $refereeModel->alias('a')
            ->join('user u','a.user_id=u.id','inner')
            ->join('user_authentication ua','a.user_id=ua.user_id','left')
            ->where('a.match_id',$row->m_id)->field('a.user_id,a.purview,ua.real_name,u.mobile')->select();
        $assignPurview = $refereeArr = [];
        foreach ($refereeInfo as $k=>$v){
            $refereeArr[] = $v['user_id'];
            $assignPurview[$v['user_id']]['purview'] = explode(',',$v['purview']);
            $assignPurview[$v['user_id']]['username'] = $v['mobile'].'_'.$v['real_name'];
        }

        $this->assign('purviewCurrent',$assignPurview);
        if ($refereeArr){
            $row->referee = implode(',',$refereeArr);
        }else{
            $row->referee = '';
        }

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {

            if ($params['sign_start_date']){
                $params['sign_start_date'] = strtotime($params['sign_start_date']);
            }

            if ($params['sign_end_date']){
                $params['sign_end_date'] = strtotime($params['sign_end_date']);
            }

            if ($params['match_date']){
                $params['match_date'] = strtotime($params['match_date']);
            }

            if (bcmod($params['people_count'],$params['group_people_number']) != 0){
                throw new Exception('赛事人数与小组人数不对等');
            }

            if (bcmod($params['group_people_number'],$params['group_inner_numbers']) != 0){
                throw new Exception('赛事组人数与小组人数不对等');
            }

            if ($params['group_people_number']==$params['group_inner_numbers']){
                throw new Exception('赛事组人数与小组人数不可相等');
            }

            if (!empty($params['release_time'])){
                $params['release_time'] = strtotime($params['release_time']);
                if($params['release_time'] >= $params['match_date']){
                    throw new Exception('发布时间不能大于赛事开始时间');
                }
            }

            if ($params['s_id'] && $storeInfo = Store::where('id',$params['s_id'])->find()){
                $params['organizer'] = $storeInfo['store_name'];
            }

            if ($params['sign_start_date'] >= $params['sign_end_date']){
                throw new Exception('报名开始时间不能大于结束时间');
            }

            if ($params['sign_end_date'] >= $params['match_date']){
                throw new Exception('赛事开始时间不能小于报名结束时间');
            }

            $addressConfig = get_addon_config('address');
            $map = new Map($addressConfig);
            $location = $params['lat'].','.$params['lng'];
            $map->getInfoByLocation($location);
            $response = $map->getResponse();
            $response = json_decode($response, true);
            if (!empty($response) && isset($response['status']) && $response['status'] == 0 && !empty($response['result']) && !empty($response['result']['address_component'])) {
                $province = $response['result']['address_component']['province'] ?: '';
                $city = $response['result']['address_component']['city'] ?: '';
                $district = $response['result']['address_component']['district'] ?: '';
                $params['province'] = Region::where('name',$province)->value('city_code');
                $params['city'] = Region::where('name',$city)->value('city_code');
                $params['district'] = Region::where('name',$district)->value('city_code');
            }
            $params['up_date'] = time();
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $where['referee'] = $referee = $params['referee'];
            unset($params['referee']);
            $result = $row->allowField(true)->save($params);
            $purviewInsert = [];
            if ($referee){
                $referee = explode(',',$referee);
                if (is_array($referee) && $referee){
                    $RefereeModel = new \app\admin\model\match\Referee();
                    foreach ($referee as $k=>$v){
                        if ($RefereeModel->where('match_id',$row->m_id)->where('user_id',$v)->find()){
                            $RefereeModel->where('match_id',$row->m_id)->where('user_id',$v)->update([
                                'purview'=>!empty($params['purview'][$v]) ? implode(',',$params['purview'][$v]) : '',
                                'update_time'=>time(),
                            ]);
                        }else{
                            $purviewInsert[] = [
                                'match_id'=>$row->m_id,
                                'user_id'=>$v,
                                'purview'=>!empty($params['purview'][$v]) ? implode(',',$params['purview'][$v]) : '',
                                'create_time'=>time(),
                                'update_time'=>time(),
                            ];
                        }

                    }
                    $RefereeModel->where('match_id',$row->m_id)->whereNotIn('user_id',$where['referee'])->delete();
                }

                if ($purviewInsert){
                    $RefereeModel = new \app\admin\model\match\Referee();
                    $RefereeModel->saveAll($purviewInsert);
                }
            }

            if(!empty($params['banner_image'])){
                $insertImage = [];
                $banner_image = explode(',',$params['banner_image']);
                if ($banner_image && is_array($banner_image)){
                    foreach ($banner_image as $k=>$v){
                        $insertImage[] = [
                            'type'=>\app\common\model\RelationImage::TYPE_MATCH,
                            'relation_id'=>$row->m_id,
                            'url'=>$v,
                            'create_time'=>time(),
                        ];
                    }
                }

                if ($insertImage){
                    $RelationImageModel = new \app\common\model\RelationImage();
                    $RelationImageModel->where('relation_id',$row->m_id)->where('type',\app\common\model\RelationImage::TYPE_MATCH)->delete();
                    $RelationImageModel->saveAll($insertImage);
                }
            }
            $adminInfo = $this->auth->getUserInfo();
            $endTime = microtime(true);
            hook('Log',[
                'username'=>$adminInfo['username'],
                'user_id'=>$adminInfo['id'],
                'tips'=>'修改赛事',
                'data'=>$params,
                'match_id'=>$row->m_id,
                'start_time'=>$startTime,
                'end_time'=>$endTime,
                'type'=>LogManager::TYPE_SERVER,
                'redirect'=>LogManager::MATCH_REDIRECT_PATH.date('Y').'/'.date('m').'/'.date('d'),
            ]);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function multi($ids=null)
    {
        $startTime = microtime(true);
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        if (false === $this->request->has('params')) {
            $this->error(__('No rows were updated'));
        }
        parse_str($this->request->post('params'), $values);
        $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
        if (empty($values)) {
            $this->error(__('You have no permission'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
            foreach ($list as $item) {
                $count += $item->allowField(true)->isUpdate(true)->save($values);
            }
            $adminInfo = $this->auth->getUserInfo();
            //print_r($adminInfo);
            $endTime = microtime(true);
            hook('Log',[
                'username'=>$adminInfo['username'],
                'user_id'=>$adminInfo['id'],
                'tips'=>'下架赛事',
                'data'=>$this->request->post(),
                'match_id'=>$ids,
                'start_time'=>$startTime,
                'end_time'=>$endTime,
                'type'=>LogManager::TYPE_SERVER,
                'redirect'=>LogManager::MATCH_REDIRECT_PATH.date('Y').'/'.date('m').'/'.date('d'),
            ]);
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }

    public function end($ids=null)
    {
        $startTime = microtime(true);
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($row->status == $this->model::STATUS_END){
            $this->error('当前赛事已结束，请勿重复操作');
        }

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $result = false;
        Db::startTrans();
        try {
            if(!$result = $this->model->where('m_id',$ids)->update(['end_time'=>time(),'status'=>$this->model::STATUS_END,'up_date'=>time()])){
                throw new Exception('结束赛事失败');
            }
            $redis = new \Redis();
            $config = config('redis');
            $redis->connect($config['host'],$config['port']);
            if ($config['password']){
                $redis->auth($config['password']);
            }
            $redis->lPush(Constant::getEndMatchListKey($config['prefix']),$ids);
            $adminInfo = $this->auth->getUserInfo();
            $endTime = microtime(true);
            hook('Log',[
                'username'=>$adminInfo['username'],
                'user_id'=>$adminInfo['id'],
                'tips'=>'结束赛事',
                'data'=>$this->request->post(),
                'match_id'=>$ids,
                'start_time'=>$startTime,
                'end_time'=>$endTime,
                'type'=>LogManager::TYPE_SERVER,
                'redirect'=>LogManager::MATCH_REDIRECT_PATH.date('Y').'/'.date('m').'/'.date('d'),
            ]);
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }

    public function cancel($ids=null)
    {
        $startTime = microtime(true);
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($row->status == $this->model::STATUS_END){
            $this->error('当前赛事已结束，请正确操作');
        }

        if ($row->status == $this->model::STATUS_CANCEL){
            $this->error('当前赛事已取消，请勿重复操作');
        }

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $result = false;
        Db::startTrans();
        try {
            $resultCancel = MatchManager::cancelMatchBySystem($ids,false);
            $result = $resultCancel['code'];
            if ($resultCancel['code']!=MatchManager::$successCode){
                throw new Exception($resultCancel['message']);
            }
            $adminInfo = $this->auth->getUserInfo();
            $endTime = microtime(true);
            hook('Log',[
                'username'=>$adminInfo['username'],
                'user_id'=>$adminInfo['id'],
                'tips'=>'取消赛事',
                'data'=>$this->request->post(),
                'match_id'=>$ids,
                'start_time'=>$startTime,
                'end_time'=>$endTime,
                'type'=>LogManager::TYPE_SERVER,
                'redirect'=>LogManager::MATCH_REDIRECT_PATH.date('Y').'/'.date('m').'/'.date('d'),
            ]);
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }

    public function ranks($ids=null)
    {
        $startTime = microtime(true);
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }


        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $result = false;
        Db::startTrans();
        try {
            $redis = new \Redis();
            $config = config('redis');
            $redis->connect($config['host'],$config['port']);
            if ($config['password']){
                $redis->auth($config['password']);
            }
            $redis->lPush(Constant::getEndMatchListKey($config['prefix']),$ids);
            $adminInfo = $this->auth->getUserInfo();
            $endTime = microtime(true);
            hook('Log',[
                'username'=>$adminInfo['username'],
                'user_id'=>$adminInfo['id'],
                'tips'=>'赛事成员排行',
                'data'=>$this->request->post(),
                'match_id'=>$ids,
                'start_time'=>$startTime,
                'end_time'=>$endTime,
                'type'=>LogManager::TYPE_SERVER,
                'redirect'=>LogManager::MATCH_REDIRECT_PATH.date('Y').'/'.date('m').'/'.date('d'),
            ]);
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('排行榜正在生成中，请耐心等候');

    }
}
